/* 
 * JS giúp tạo các loại biểu đồ
 * Khi sử dụng phải gọi tới thư viện: 
 * 
 <script src="/js/jquery.flot.min.js"></script>
 <script src="/js/jquery.flot.pie.js"></script>
 <script src="/js/jquery.flot.orderBars.js"></script>
 <script src="/js/jquery.flot.resize.js"></script>
 */



//*********************   Charts   *********************//	
//*Interacting with the data points *//
$(function () {
    // CHARts        


    /* table chart */
    $("table.chart2").each(function () {
        var colors = [];
        $("table.chart thead th:not(:first)").each(function () {
            colors.push($(this).css("color"));
        });
        $(this).graphTable({
            series: 'columns',
            position: 'replace',
            width: '100%',
            height: '250px',
            colors: colors
        }, {
            xaxis: {
                tickSize: 1,
            },
            yaxis: {
                max: 1000,
                min: 200,
            },
            series: {
                points: {
                    show: true
                },
                lines: {
                    show: true,
                    fill: false,
                    steps: false
                },
            }
        });
    });



    function showTooltip(x, y, contents) {
        $('<div id="tooltip" >' + contents + '</div>"').css({
            position: 'absolute',
            display: 'none',
            top: y - 13,
            left: x + 10
        }).appendTo("body").show();
    }

    var previousPoint = null;
    $(".chart_flot").bind("plothover", function (event, pos, item) {

        $("#x").text(pos.x);
        $("#y").text(pos.y);

        if (item) {
            if (previousPoint != item.dataIndex) {
                previousPoint = item.dataIndex;

                $(this).attr('title', item.series.label);
                $(this).trigger('click');
                $("#tooltip").remove();
                var x = item.datapoint[0],
                        y = item.datapoint[1];

                showTooltip(item.pageX, item.pageY, "<p>Info for a day</p><b>" + item.series.label + "</b> : " + y);
            }
        } else {
            $("#tooltip").remove();
            previousPoint = null;
        }
    });

});
//* BAR *//


$(function () {
    var previousPoint;
    var d1 = [];
    for (var i = 0; i <= 7; i += 1)
        d1.push([i, parseInt(Math.random() * 30)]);

    var d2 = [];
    for (var i = 0; i <= 7; i += 1)
        d2.push([i, parseInt(Math.random() * 30)]);

    var d3 = [];
    for (var i = 0; i <= 7; i += 1)
        d3.push([i, parseInt(Math.random() * 30)]);

    var ds = new Array();

    ds.push({
        data: d1,
        bars: {
            show: true,
            barWidth: 0.2,
            order: 1,
            lineWidth: 2
        }

    });
    ds.push({
        data: d2,
        bars: {
            show: true,
            barWidth: 0.2,
            order: 2
        }
    });
    ds.push({
        data: d3,
        bars: {
            show: true,
            barWidth: 0.2,
            order: 3
        }
    });

    //tooltip function
    function showTooltip(x, y, contents, areAbsoluteXY) {
        var rootElt = 'body';

        $('<div id="tooltip" class="tooltip-with-bg">' + contents + '</div>').css({
            position: 'absolute',
            display: 'none',
            'z-index': '1010',
            top: y,
            left: x,
            border: '1px solid #d5d5de',
            padding: '3px',
            'background-color': '#ffffff',
        }).prependTo(rootElt).show();
    }

    //Display graph
    $.plot($(".bars"), ds, {
        grid: {
            hoverable: true
        }
    });

    //Display horizontal graph
    var d1_h = [];
    for (var i = 0; i <= 5; i += 1)
        d1_h.push([parseInt(Math.random() * 30), i]);

    var d2_h = [];
    for (var i = 0; i <= 5; i += 1)
        d2_h.push([parseInt(Math.random() * 30), i]);

    var d3_h = [];
    for (var i = 0; i <= 5; i += 1)
        d3_h.push([parseInt(Math.random() * 30), i]);

    var ds_h = new Array();
    ds_h.push({
        data: d1_h,
        bars: {
            horizontal: true,
            show: true,
            barWidth: 0.2,
            order: 1,
            lineWidth: 2

        }
    });
    ds_h.push({
        data: d2_h,
        bars: {
            horizontal: true,
            show: true,
            barWidth: 0.2,
            order: 2
        }
    });
    ds_h.push({
        data: d3_h,
        bars: {
            horizontal: true,
            show: true,
            barWidth: 0.2,
            order: 3
        }
    });


    //add tooltip event
    $(".bars").bind("plothover", function (event, pos, item) {
        if (item) {
            if (previousPoint != item.datapoint) {
                previousPoint = item.datapoint;

                //delete de precedente tooltip
                $('.tooltip-with-bg').remove();

                var x = item.datapoint[0];

                //All the bars concerning a same x value must display a tooltip with this value and not the shifted value
                if (item.series.bars.order) {
                    for (var i = 0; i < item.series.data.length; i++) {
                        if (item.series.data[i][3] == item.datapoint[0])
                            x = item.series.data[i][0];
                    }
                }

                var y = item.datapoint[1];

                showTooltip(item.pageX + 5, item.pageY + 5, x + " = " + y);

            }
        }
        else {
            $('.tooltip-with-bg').remove();
            previousPoint = null;
        }

    });




    /* Pie charts */

    $(function () {
        var data = [];
        var series = Math.floor(Math.random() * 10) + 1;
        for (var i = 0; i < series; i++)
        {
            data[i] = {
                label: "Series" + (i + 1),
                data: Math.floor(Math.random() * 100) + 1
            }
        }

        $.plot($("#graph1"), data,
                {
                    series: {
                        pie: {
                            show: true,
                            radius: 1,
                            label: {
                                show: true,
                                radius: 2 / 3,
                                formatter: function (label, series) {
                                    return '<div style="font-size:11px;text-align:center;padding:2px;color:white;">' + label + '<br/>' + Math.round(series.percent) + '%</div>';
                                },
                                threshold: 0.1
                            }
                        }
                    },
                    legend: {
                        show: false
                    },
                    grid: {
                        hoverable: false,
                        clickable: true
                    },
                });
        $("#interactive").bind("plothover", pieHover);
        $("#interactive").bind("plotclick", pieClick);

        $.plot($("#graph2"), data,
                {
                    series: {
                        pie: {
                            show: true,
                            radius: 300,
                            label: {
                                show: true,
                                formatter: function (label, series) {
                                    return '<div style="font-size:11px;text-align:center;padding:2px;color:white;">' + label + '<br/>' + Math.round(series.percent) + '%</div>';
                                },
                                threshold: 0.1
                            }
                        }
                    },
                    legend: {
                        show: false
                    },
                    grid: {
                        hoverable: false,
                        clickable: true
                    }
                });
        $("#interactive").bind("plothover", pieHover);
        $("#interactive").bind("plotclick", pieClick);
    });

    function pieHover(event, pos, obj)
    {
        if (!obj)
            return;
        percent = parseFloat(obj.series.percent).toFixed(2);
        $("#hover").html('<span style="font-weight: bold; color: ' + obj.series.color + '">' + obj.series.label + ' (' + percent + '%)</span>');
    }
    function pieClick(event, pos, obj)
    {
        if (!obj)
            return;
        percent = parseFloat(obj.series.percent).toFixed(2);
        alert('' + obj.series.label + ': ' + percent + '%');
    }



    /* Updating graphs real-time */
    $(function () {
        // we use an inline data source in the example, usually data would
        // be fetched from a server
        var data = [], totalPoints = 300;
        function getRandomData() {
            if (data.length > 0)
                data = data.slice(1);

            // do a random walk
            while (data.length < totalPoints) {
                var prev = data.length > 0 ? data[data.length - 1] : 50;
                var y = prev + Math.random() * 10 - 5;
                if (y < 0)
                    y = 0;
                if (y > 100)
                    y = 100;
                data.push(y);
            }

            // zip the generated y values with the x values
            var res = [];
            for (var i = 0; i < data.length; ++i)
                res.push([i, data[i]])
            return res;
        }

        // setup control widget
        var updateInterval = 1000;
        $("#updateInterval").val(updateInterval).change(function () {
            var v = $(this).val();
            if (v && !isNaN(+v)) {
                updateInterval = +v;
                if (updateInterval < 1)
                    updateInterval = 1;
                if (updateInterval > 2000)
                    updateInterval = 2000;
                $(this).val("" + updateInterval);
            }
        });

        // setup plot
        var options = {
            series: {
                shadowSize: 0
            }, // drawing is faster without shadows
            yaxis: {
                min: 0,
                max: 120
            },
            xaxis: {
                show: false
            },
            colors: ["#2686d2"],
            series: {
                lines: {
                    lineWidth: 1,
                    fill: true,
                    fillColor: {
                        colors: [{
                                opacity: 0.5
                            }, {
                                opacity: 1.0
                            }]
                    },
                    steps: false,
                    show: true

                },
                points: {
                    show: false
                }
            }
        };
        var plot = $.plot($(".autoUpdate"), [getRandomData()], options);

        function update() {
            plot.setData([getRandomData()]);
            // since the axes don't change, we don't need to call plot.setupGrid()
            plot.draw();

            setTimeout(update, updateInterval);
        }

        update();
    });


});
//////////////////////

/* pieChart (Round Infographic) */
var initPieChart = function () {
    $('.percentage').easyPieChart({
        animate: 1000
    });
    $('.percentage-light').easyPieChart({
        barColor: function (percent) {
            percent /= 100;
            return "rgb(" + Math.round(255 * (1 - percent)) + ", " + Math.round(255 * percent) + ", 0)";
        },
        trackColor: '#ebebeb',
        scaleColor: false,
        lineCap: 'butt',
        lineWidth: 10,
        animate: 1000
    });

    $('.updateEasyPieChart').on('click', function (e) {
        e.preventDefault();
        $('.percentage, .percentage-light').each(function () {
            var newValue = Math.round(100 * Math.random());
            $(this).data('easyPieChart').update(newValue);
            $('span', this).text(newValue);
        });
    });
};